package magics
{
	import core.actor.core.ActorView;
	
	import battle.battleFightData.BattleData;
	import battle.battleFightData.XMLDataLoader;
	
	import flash.display.FrameLabel;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class BattleCombiner implements ITickable
	{
		private var _scene:Sprite;
		private var _attacker:ActorView;
		private var _mainTarget:ActorView;
		private var _targets:Vector.<ActorView>;
		
		private var _curFrame:int = 0;
		private var _totalFrame:int = 0;
		
		private var _moveFrameCount:int = 0;
		private var _moveFrames:Array = [5,10,20,30];
		private var _speed:Point = null;
		private var _aniData:Vector.<BattleData>;
		
		private var _attackerOriginPos:Point;
		private var _targetsOriginPos:Vector.<Point>;
		
		private var _magics:Array;
		
		public function BattleCombiner()
		{
			_magics = [];
		}
		
		/**
		 * 临时添加获取当前帧数和总帧数的方法
		 * 
		 * */
		public function get curFrame():int
		{
			return _curFrame;
		}
		
		public function get totalFrame():int
		{
			return _totalFrame;
		}
		
		public function get speed():Number
		{
			if(_speed != null)
				return _speed.x;
			else
				return -1;
		}
		
		
		/**初始化
		 *魔法由action文件中的名字直接读取，不需要外部设置
		 * */
		public function initAni(aniUrl:String):void
		{
			//骨骼动画	
			//测试用读取方式
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE,aniLoadComplete);
			urlLoader.load(new URLRequest(aniUrl));
		}
		
		private function aniLoadComplete(e:Event):void
		{
			var xml:XML = XML(e.target.data);
			var d:XMLDataLoader = new XMLDataLoader();
			d.fromXml(xml);
			_aniData = d.battleFrames;
			_moveFrames = d.moveTimeArray;
			_totalFrame = _aniData.length;
		}
		
		public function setScene(scene:Sprite):void
		{
			//屏幕；震动，移动的对象	
			//TODO：震屏，move Focus
			_scene = scene;
			ScreenShock.setTarget(_scene);
		}
		
		public function setAttacker(fighter:ActorView):void
		{
			//攻击者
			//TODO：控制小人跑动
			_attacker = fighter;
			_attackerOriginPos = new Point(_attacker.x,_attacker.y);
		}
		
		public function setTarget(actors:Vector.<ActorView>,mainTarget:ActorView = null):void
		{
			//被攻击者
			_targets = actors;
			_targetsOriginPos = new Vector.<Point>();
			for(var i:int = 0;i<_targets.length;i++)
			{
				_targetsOriginPos[i] = new Point(_targets[i].x,_targets[i].y);
			}
			if(mainTarget != null)
				_mainTarget = mainTarget;
			else
				_mainTarget = actors[0];
				
		}
		
		public function setBloodType(type:String):void
		{
			//设置冒血类型
			//TODO：设置相应冒血动画读取
			if(type == "normal")
			{
				loadNumPic();
				loadBloodEffect("../testRes/bloodNumt.swf");
			}
		}
		
		private var _bloodEffect:MovieClip;
		private var _numBitmapData:Array=[];
		private var _isLoadingNumPic:Boolean = false;
		private var _numPicLoaded:Boolean = false;
		private var _needInitBloodNum:int = 0;
		
		//应在初始化loader中load冒血数字信息
		private function loadNumPic():void
		{
			if(_isLoadingNumPic) return;
			_isLoadingNumPic = true;
			_numPicLoaded = false;
			for(var i:int=0;i<10;i++)
			{
				var tloader:Loader=new Loader;
				tloader.load(new URLRequest("../testRes/picts/"+i+".png"));
				tloader.contentLoaderInfo.addEventListener(Event.COMPLETE,initNum)
				tloader.name=i.toString();
			}
		}
		
		private function initNum(event:Event):void{
			//numBitmapData.push(event.target.content.bitmapData);
			event.target.removeEventListener(Event.COMPLETE,initNum);
			_numBitmapData[event.target.loader.name]=event.target.content.bitmapData;
			if(_numBitmapData.length == 10)
			{
				_numPicLoaded = true;
				if(_bloodEffect!=null)
				{
					_bloodEffect.init(_numBitmapData);
					if(_needInitBloodNum!=0)
					{
						_bloodEffect.setMovie(_needInitBloodNum);
						_needInitBloodNum = 0;
					}
				}
			}
			
		}
		
		private function loadBloodEffect(url:String):void{
			var mcLoader:Loader = new Loader();
			var urlRequest:URLRequest=new URLRequest(url);
			mcLoader.load(urlRequest);
			mcLoader.contentLoaderInfo.addEventListener(Event.INIT,bloodLoadComplete);
		}
		
		private function bloodLoadComplete(event:Event):void
		{
			event.target.removeEventListener(Event.INIT,bloodLoadComplete);
			_bloodEffect=event.target.content;
			if(_numBitmapData.length == 10)
			{
				_bloodEffect.init(_numBitmapData);
				if(_needInitBloodNum!=0)
				{
					_bloodEffect.setMovie(_needInitBloodNum);
					_needInitBloodNum = 0;
				}
			}
		}
		
		public function setBloodNum(num:Number):void
		{
			if(_bloodEffect!=null)
				_bloodEffect.setMovie(num);
			else
				_needInitBloodNum = num;
			//设置冒血数字
		}
		
		/****************************初始化结束***********************************/
		
		
		/*********************************test***********************************/
		
		private var s:Sprite= new Sprite();
		public function testFocus(targetOffset:Number):void
		{
			//,
			//s.x = 0;
			TweenLite.to(_scene,.5,{x:targetOffset,onComplete:onFocusCompleteP1,onCompleteParams:[targetOffset]});
		}
		
		private function onFocusCompleteP1(offset:Number):void
		{
			TweenLite.to(_scene,.5,{x:0});
		}
		
		public function testZoom(zoom:Number):void
		{
			s.x = 1;
			TweenLite.to(s,2,{x:zoom,onUpdate:updateHandler,onComplete:completeHandler});
		}
		
		private function updateHandler():void
		{
			zoom(s.x);
		}
		
		private function completeHandler():void
		{
			zoom(1);
		}
		
		public function testShake():void
		{
			shake(0);			
		}
		
		public function testMoveActor():void
		{
			TickManager.instance.addObject(this);
		}
		
		public function testBlood():void
		{
			if(_bloodEffect!=null)
			{
				if(!_scene.contains(_bloodEffect))
				{
					_scene.addChild(_bloodEffect);
				}
				//_bloodEffect.x = bd.texts[0].x;
				//_bloodEffect.y = bd.texts[0].y;
				_bloodEffect.playAll();
			}
		}
		
		
		/************************************************************************/
		
		private function  setFocusOffset(focusOffset:Number):void
		{
			_scene.x = focusOffset;
		}
			
		private function shake(type:int):void
		{
			ScreenShock.addShock(0,20,90); 
		}
		
		private function zoom(zoom:Number):void
		{
			_scene.scaleX = zoom;
			_scene.scaleY = zoom;
		}
			
		
		
		private function getAttackerStandardPos(curFrame:int,speed:Point):Point
		{
			//判断是跑步的第几帧,乘以速度，获取当前位置,使用此方法设置角色位置
			var curMoveFrame:int = getMoveFrame(curFrame,_moveFrames);
			return new Point(_attackerOriginPos.x+curMoveFrame*speed.x,_attackerOriginPos.y+curMoveFrame*speed.y);
		}
		
		private function initMoveSpeed(moveFrameCount:int):Point
		{
			var xSpeed:Number = (_mainTarget.x - _attacker.x)/moveFrameCount;
			var ySpeed:Number = (_mainTarget.y - _attacker.y)/moveFrameCount;
			return new Point(xSpeed,ySpeed);
		}
		
		/**
		 * 测试获取角色移动帧数
		 * */
		public function get moveFrame():int
		{
			if(_moveFrames!=null)
				return getMoveFrame(_curFrame,_moveFrames);
			else 
				return -1;
		}
		
		private function getMoveFrame(curFrame:int,moveFrameInfo:Array):int
		{
			var moveFrameCount:int = 0;
			for(var i:int = 0;i<moveFrameInfo.length;i++)
			{
				if(i%2 != 0)
				{
					moveFrameCount += moveFrameInfo[i] - moveFrameInfo[i-1];
				}
				if(i == 0 && curFrame<=moveFrameInfo[0])
				{
					break;
				}
				else
				{
					if(curFrame<=moveFrameInfo[i] && curFrame> moveFrameInfo[i-1])
					{
						if(i%2 == 0)
						{
							if(curFrame == moveFrameInfo[i])
							{
								//moveFrameCount+=1;//是否需要+1?
							}
						}
						else
						{
							moveFrameCount+=curFrame - moveFrameInfo[i-1];
							moveFrameCount -= moveFrameInfo[i] - moveFrameInfo[i-1];
						}
						
						break;
					}
				}
				//插入排序，找到插入位置，判断是在区间内还是区间外
				//找到后，累加前面每两个数的差，即是move的当前帧
				//寻找高效插入算法	
			}
			return moveFrameCount;
		}
		
		private function getMoveFrameCount(moveFrameInfo:Array):void
		{
			for(var i:int = 0;i<moveFrameInfo.length;i=i+2)
			{
				_moveFrameCount += int(moveFrameInfo[i+1])-int(moveFrameInfo[i]);
			}
		}
		
		private function beginAttackerMove():void
		{
			getMoveFrameCount(_moveFrames);
			_speed = initMoveSpeed(_moveFrameCount);
		}
		
	
		private function startAttackerAction(actionName:String):void
		{
			//_attacker.initAni()
		}
		
		private function startTargetsAction():void
		{
			
		}
		
		private function setTargetsProperty(propertyName:String,p:Object):void
		{
			//魔法和攻击者都比较容易取到，故只有一个设置攻击目标的数组	
		}
		
		
		public function play():void
		{
			beginAttackerMove();
			TickManager.instance.addObject(this);
		}
		
		public function update(step:int):void
		{
			if(_curFrame == _totalFrame-1)
			{
				stop();
				_curFrame = 0;
				return;
			}
			
			var bd:BattleData = _aniData[_curFrame];
			if(bd.fighter!=null)
			{
				var pos:Point = getAttackerStandardPos(_curFrame,_speed); 
				_attacker.x = pos.x;
				_attacker.y = pos.y;
				if(bd.fighter.offsetX!=NaN)
					_attacker.x += bd.fighter.offsetX;
				if(bd.fighter.offsetY!=NaN)
					_attacker.y += bd.fighter.offsetY;
				if(bd.fighter.isReverse)
					_attacker.direction = 1;
				else
					_attacker.direction = 0;
				if(bd.fighter.actionName!="")
				{
					var loop:Boolean = bd.fighter.actionName == "walk"?true:false;
					_attacker.doAction(bd.fighter.actionName,loop);
					//TODO:做动作
				}
			}
			if(bd.target!=null)
			{
				for(var i:int = 0;i<_targets.length;i++)
				{
					if(bd.target.offsetX!=NaN)
						_targets[i].x = _targetsOriginPos[i].x + bd.target.offsetX;
					if(bd.target.offsetY!=NaN)
						_targets[i].y = _targetsOriginPos[i].y + bd.target.offsetY;
					if(bd.target.isReverse)
						_targets[i].direction = 1;
					else
						_targets[i].direction = 0;
					if(bd.target.actionName!="")
					{
						_targets[i].doAction(bd.fighter.actionName);
					}
				}
			}
			if(bd.magic!=null)
			{
				if(bd.magic.name!="")
				{
					//TODO:替换为从缓存中取magic对象
					var magic:Magic;
					if(_magics[bd.magic.name]!=null)
						magic = _magics[bd.magic.name] as Magic;
					else
					{
						magic= new Magic();
						magic.init(this._scene);
						magic.initAni("../testRes/ani/"+bd.magic.name+".xml");//TODO:路径从PathHelper中取，或从缓存中取
						_magics[bd.magic.name] = magic;	
					}
					magic.play();
					magic.setProperty("x",500);//TODO:根据目标位置进行调整
					magic.setProperty("y",250);
				}
			}
			if(bd.texts!=null)
			{
				//testBlood();
				if(_bloodEffect!=null)
				{
					if(!_scene.contains(_bloodEffect))
					{
						_scene.addChild(_bloodEffect);
					}
					_bloodEffect.x = bd.texts[0].x;
					_bloodEffect.y = bd.texts[0].y;
					_bloodEffect.playAll();
				}
				
			}
			if(bd.camera!=null)
			{
				//setFocusOffset(-bd.camera.offsetX);
			}
			if(bd.effect!=null)
			{
				if(bd.effect.name == "shake")
					testShake();
			}
			_curFrame++;
			
		}
		
		
		public function stop():void
		{
			TickManager.instance.removeObject(this);
			//reset position,重置全局设置
			_attacker.x = _attackerOriginPos.x;
			_attacker.y = _attackerOriginPos.y;
			for(var i:int = 0;i<_targets.length;i++)
			{
				_targets[i].x = _targetsOriginPos[i].x;
				_targets[i].y = _targetsOriginPos[i].y;
			}
			_moveFrameCount = 0;
		}
		
		public function get tickType():int
		{
			return 0;	
		}
		
		public function clear():void
		{
			
		}
	}
}